<template>
    <div class="ct-bodySet">
        <el-container>
            <el-header  class="bgclr-dk-sp0 mb20 headerCoster" style="position: fixed; z-index: 101; left: 200px; top: 60px; right: 0;">
                <el-breadcrumb  separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/mainPage/welcome' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>系统管理</el-breadcrumb-item>
                    <el-breadcrumb-item><span class="main-Clr-ft">菜单管理</span></el-breadcrumb-item>
                </el-breadcrumb>
            </el-header>
            <el-container  class="pl20 pr20 mt80 disFlex">
                <el-card  class="mr15 leftMinWidth autoHeight">
                    <div slot="header">
                        <span>菜单管理</span>
                    </div>
                    <el-tree :data="menuTreeData" :props="menuTreeDataProps" ref="menuTree" default-expand-all highlight-current
                             :expand-on-click-node="false" node-key="id"@node-click="handleNodeClick">
                            <span slot-scope="{ node, data }">
                                <span class="labelstyleTree tx-Elps" :title="node.label" v-if="data.id!==''" >{{ node.label }}</span>
                                <span class="labelstyleTree tx-Elps main-Clr-ft" v-else :title="node.label">{{ node.label }}</span>
                                <span v-if="onlyAdd(data.id)"><el-button type="text" icon="iconfont icon-tianjia" @click.stop="menuAppend(data)"></el-button></span>
                                    <span v-else-if="data.id">
                                        <i class="iconfont icon-tianjia main-Clr-ft ml2 mr2" title="添加" @click.stop="menuAppend(data)"></i>
                                        <i class="iconfont icon-shanchu main-Clr-ft" title="删除" v-if="treeRemove(data.children.length)" @click.stop="() =>menuRemove(node, data)"></i>
                                    </span>
                                    <span v-else><el-button icon="iconfont icon-shanchu" title="取消添加" type="text" v-if="treeRemove(data.children.length)" @click.stop="() =>menuRemove(node, data)"></el-button></span>
                            </span>
                    </el-tree>
                </el-card>
                <el-card v-show="showFlag" class="cardAllWidth autoHeight RightFlex">
                    <div slot="header">
                            <span v-if="flage">
                                新建<span class=" main-Clr-ft ml2 mr2">{{ oldParentName }}</span>的下级菜单
                            </span>
                        <span v-else >当前编辑菜单<span class="main-Clr-ft"> {{ oldName }}</span></span>
                    </div>
                    <el-form  :model="formData" ref="formData" :rules="formRules" label-width="18%">
                        <el-form-item label="菜单名称:" prop="name">
                            <el-input placeholder="请输入菜单名称" v-model.trim="formData.name" size="small" class="formLayoutW"></el-input>
                        </el-form-item>
                        <el-form-item label="请求路径:" prop="path">
                            <el-input placeholder="请输入菜单请求路径" v-model.trim="formData.path" size="small" class="formLayoutW"></el-input>
                        </el-form-item>
                        <el-form-item label="菜单编号:">
                            <el-col class="formLayoutW" v-if="flage">提交后系统创建</el-col>
                            <el-col class="formLayoutW" v-else>{{formData.id}}</el-col>
                        </el-form-item>

                        <el-form-item label="显示状态:" prop="ifShow">
                            <el-switch
                                    v-model="formData.ifShow"
                                    active-text="显示"
                                    inactive-text="不显示">
                            </el-switch>
                        </el-form-item>

                        <el-form-item label="可用状态:" prop="enable">
                            <el-switch
                                    v-model="formData.enable"
                                    active-text="可用"
                                    inactive-text="不可用">
                            </el-switch>
                        </el-form-item>

                        <el-form-item label="菜单顺序:" prop="orderid">
                            <el-input placeholder="请输入菜单顺序" type="number" v-model.trim="formData.orderid" size="small" class="formLayoutW"></el-input>
                        </el-form-item>
                        <el-form-item label="菜单图标:" prop="icon">
                            <el-input placeholder="请输入图标位置" v-model.trim="formData.icon" size="small" class="formLayoutW"></el-input>
                        </el-form-item>
                        <el-form-item label="菜单描述:"  prop="description">
                            <el-input placeholder="请输入菜单描述" size="small" type="textarea" :rows="8" v-model.trim="formData.description" class="formLayoutW"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" @click="submitForm('formData')">提交</el-button>
                            <el-button class="bkmgColor" size="small" v-if="flage" @click="resetForm('formData')">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-container>
            <div class="bottomLayoutBus"></div>
        </el-container>
    </div>
</template>

<script>
    import Vue from 'vue';
    import urlConfig from '../../../config/url.json';
    import { Message } from 'element-ui';

    Vue.component(Message.name,Message);
    export default {
        data() {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入菜单顺序'));
                } else {
                    if(!/^[0-9]+$/.test(value)) {
                        callback(new Error('菜单顺序必须为数字'));
                    }
                    callback();
                }
            };
            return {
                flage:false,                            //标记是否添加
                showFlag:false,
                oldId:'',
                oldName:'',
                oldPath:'',
                oldorderid:'',
                oldIcon:'',
                oldDescription:'',
                oldIfShow:false,                              //是否显示
                oldEnable:false,                              //是否可用
                formData: {
                    id:'',
                    name:'',
                    path:'',
                    orderid:'',
                    icon:'',
                    description:'',
                    parentId:'',
                    ifShow: '',
                    enable: '',
                    children:[]
                },
                formRules:{
                    name:[
                        { required: true, message: '请输入菜单名称', trigger: 'blur' },
                        {  max: 100, message: '长度在100个字符以内', trigger: 'blur' }
                    ],
                    path:[
                        { required: true, message: '请输入菜单请求路径', trigger: 'blur' },
                        {  max: 255, message: '长度在255个字符以内', trigger: 'blur' }
                    ],
                    orderid:[
                        { required: true,validator: validatePass, trigger: 'blur'},
                        {  max: 3, message: '长度在3个字符以内', trigger: 'blur' }
                    ],
                    icon:[
                        {  max: 255, message: '长度在255个字符以内', trigger: 'blur' }
                    ],
                    description:[
                        {  max: 255, message: '长度在255个字符以内', trigger: 'blur' }
                    ],
                    ifShow:[
                        {  required: true, trigger: 'blur' }
                    ],
                    enable:[
                        {  required: true, trigger: 'blur' }
                    ]
                },
                menuTreeData: [{
                    id:-1,
                    name:'菜单根结点',
                    children:[]
                }],
                menuTreeDataProps:{
                    children: 'children',
                    label: 'name',
                },
                oldParentName:''
            }
        },
        methods:{

            onlyAdd(id){
                return id=='-1';
            },

            treeRemove(length){
                return length==0;
            },

            //选择树节点时触发
            handleNodeClick(data) {
                if(data.id=='-1'){
                    //如果点击的是虚拟根节点 不做任何操作
                    return;
                }
                let that = this;
                if (that.flage) {
                    //添加过程中不允许做其他操作
                    Message.warning('请先完成本次添加');
                } else if(!that.formChange()){
                    //修改过程中  点击其他节点弹出提示
                    this.$confirm('是否取消当前操作', '警告', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        //点击'是'之后
                        that.formData.id = that.oldId;
                        that.formData.name = that.oldName;
                        that.formData.path = that.oldPath;
                        that.formData.orderid = that.oldorderid;
                        that.formData.icon = that.oldIcon;
                        that.formData.description = that.oldDescription;
                        that.formData.ifShow = that.oldIfShow;
                        that.formData.enable = that.oldEnable;
                        this.$message({
                            type: 'info',
                            message: '操作已取消'
                        });
                    }).catch(() => {
                        //点击'否'之后
                        this.$message({
                            type: 'info',
                            message: '请继续操作'
                        });
                        this.$refs.menuTree.setCurrentKey(that.oldId);
                    });
                }
                else{
                    that.getMenuInfoByMenuId(data.id);//查询菜单信息
                    }
                },
                //通过菜单id查询菜单信息
                getMenuInfoByMenuId(id){
                    let that = this;
                    that.$refs['formData'].clearValidate();
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                    });
                    this.$http({
                            method: 'get',
                            url: urlConfig.getMenuInfoByMenuId,
                            baseURL: '/api',
                            params: {
                                id: id
                            }
                        }
                    ).then(function (response) {
                        if (response.data.code==200) {
                            if (!response.data.data) {
                                return;
                            }
                            that.showFlag = true;
                            that.formData = response.data.data.bgMenu;
                            //点击节点后 对比用的属性值 需要跟表单值同步
                            that.oldId = response.data.data.bgMenu.id;
                            that.oldName = response.data.data.bgMenu.name;
                            that.oldPath = response.data.data.bgMenu.path;
                            that.oldorderid = response.data.data.bgMenu.orderid;
                            that.oldIcon = response.data.data.bgMenu.icon;
                            that.oldDescription = response.data.data.bgMenu.description;

                            //判断是否显示
                            if(response.data.data.bgMenu.ifShow===1){
                                that.oldIfShow=true;
                                that.formData.ifShow=true;
                            }else{
                                that.oldIfShow=false;
                                that.formData.ifShow=false;
                            }

                            //判断是否可用
                            if(response.data.data.bgMenu.enable===1){
                                that.oldEnable=true;
                                that.formData.enable=true;
                            }else{
                                that.oldEnable=false;
                                that.formData.enable=false;
                            }
                        }else{
                            Message.error('获取失败')
                        }
                        loading.close();
                    }).catch(function (err) {
                        Message.error('获取失败');
                        loading.close();
                    });
                },
            //添加节点触发
            menuAppend(data){
                let that = this;
                if (that.flage) {
                    //添加过程中  点击其他添加按钮弹出提示
                    Message.warning('请先完成本次添加');
                } else if(!that.formChange()) {
                    //修改过程中  点击其他添加按钮弹出提示
                    this.$confirm('是否放弃本次修改', '警告', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.formData.id = that.oldId;
                        that.formData.name = that.oldName;
                        that.formData.path = that.oldPath;
                        that.formData.orderid = that.oldorderid;
                        that.formData.icon = that.oldIcon;
                        that.formData.description = that.oldDescription;
                        that.formData.ifShow = that.oldIfShow;
                        that.formData.enable = that.oldEnable;
                        this.$message({
                            type: 'info',
                            message: '操作已取消'
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '请继续操作'
                        });
                        this.$refs.menuTree.setCurrentKey(that.oldId);
                    })
                }
                else {
                    that.showFlag = true;
                    that.$refs['formData'].clearValidate();
                    const newChild = {
                        id: '',
                        name: '新菜单',
                        path: '',
                        parentId: data.id,
                        orderid: '',
                        icon: '',
                        description: '',
                        ifShow:true,
                        enable:true,
                        children: []
                    };
                    if (!data.children) {
                        this.$set(data, 'children', []);
                    }
                    data.children.push(newChild);
                    that.formData = newChild;
                    that.oldId = newChild.id;
                    that.oldName = newChild.name;
                    that.oldPath = newChild.path;
                    that.oldorderid = newChild.orderid;
                    that.oldIcon = newChild.icon;
                    that.oldDescription = newChild.description;
                    that.oldIfShow = newChild.ifShow;
                    that.oldEnable = newChild.enable;
                    that.oldParentName = data.name;
                    that.flage = true;
                }
            },
            menuRemove(node, data) {
                let that =this;
                if(!data.id){
                    //添加过程中  点击其他删除按钮弹出提示
                    this.$confirm('是否取消当前操作', '警告', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        const parent = node.parent;
                        const children = parent.data.children || parent.data;
                        const index = children.findIndex(d => d.id === data.id);
                        children.splice(index, 1);
                        that.flage=false;
                        that.showFlag = false;
                        that.formData.id = that.oldId;
                        that.formData.name = that.oldName;
                        that.formData.path = that.oldPath;
                        that.formData.orderid = that.oldorderid;
                        that.formData.icon = that.oldIcon;
                        that.formData.description = that.oldDescription;
                        that.formData.ifShow = that.oldIfShow;
                        that.formData.enable = that.oldEnable;
                        that.$refs['formData'].clearValidate();
                        this.$message({
                            type: 'info',
                            message: '操作已取消'
                        });
                        this.menuRequest('',1);
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '请继续操作'
                        });
                    });
                }
                else if (that.flage) {
                    Message.warning('请先完成本次添加');
                } else if(!that.formChange()) {
                    this.$confirm('是否取消当前操作', '警告', {
                        confirmButtonText: '是',
                        cancelButtonText: '否',
                        type: 'warning'
                    }).then(() => {
                        that.formData.id = that.oldId;
                        that.formData.name = that.oldName;
                        that.formData.path = that.oldPath;
                        that.formData.orderid = that.oldorderid;
                        that.formData.icon = that.oldIcon;
                        that.formData.description = that.oldDescription;
                        that.formData.ifShow = that.oldIfShow;
                        that.formData.enable = that.oldEnable;
                        that.$refs.menuTree.setCurrentKey(that.oldId);
                        this.$message({
                            type: 'info',
                            message: '操作已取消'
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '请继续操作'
                        });
                        this.$refs.menuTree.setCurrentKey(that.oldId);
                    });
                }else {
                    that.$refs['formData'].clearValidate();
                    this.$confirm('确定要删除    <span class="main-Clr-ft">' + data.name + '</span>    菜单项吗？', '温馨提示', {
                        dangerouslyUseHTMLString: true,
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let that =this;
                        that.$refs['formData'].clearValidate();
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                        });
                        this.$http({
                            method: 'delete',
                            url: urlConfig.menuManage,
                            baseURL: '/api',
                            data: {
                                "id": data.id,
                            }
                        }).then(function (response) {
                            if (response.data.code > 199 && response.data.code < 400) {
                                Message.success('删除成功');
                                that.showFlag=false;
                            }else{
                                Message.error('删除失败')
                            }
                            loading.close();
                            that.menuRequest('',1)
                        }).catch(function (err) {
                            Message.error('删除失败');
                            loading.close();
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            submitForm(formName) {
                let that = this;

                let ifShowNum;
                //根据true/false值转换为1/0值
                if(that.formData.ifShow){
                    ifShowNum=1;
                }else{
                    ifShowNum=0;
                }

                let enableNum;
                //根据true/false值转换为1/0值
                if(that.formData.enable){
                    enableNum=1;
                }else{
                    enableNum=0;
                }
                if(that.flage) {
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            let that = this;
                            const loading = this.$loading({
                                lock: true,
                                text: 'Loading',
                                spinner: 'el-icon-loading',
                            });
                            this.$http({
                                method: 'post',
                                url: urlConfig.menuManage,
                                baseURL: '/api',
                                data: {
                                    "name": that.formData.name,
                                    "path": that.formData.path,
                                    "order": that.formData.orderid,
                                    "parentId": that.formData.parentId,
                                    "icon":that.formData.icon,
                                    "description":that.formData.description,
                                    "ifShow":ifShowNum,
                                    "enable":enableNum,
                                }
                            }).then(function (response) {
                                if (response.data.code > 199 && response.data.code < 400) {
                                    Message.success('添加成功');
                                    that.formData.id = response.data.data.id;
                                    that.oldId = that.formData.id;
                                    that.oldName = that.formData.name;
                                    that.oldPath = that.formData.path;
                                    that.oldorderid = that.formData.orderid;
                                    that.oldIcon = that.formData.icon;
                                    that.oldDescription = that.formData.description;
                                    that.menuRequest('',1);
                                }else {
                                    Message.error('添加失败');
                                }
                                that.flage=false;
                                loading.close();
                            }).catch(function (err) {
                                Message.error('添加失败');
                                that.flage=false;
                                that.menuRequest('',1);
                                loading.close();
                            });
                        }
                    });
                }
                else{
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            let that = this;
                            const loading = this.$loading({
                                lock: true,
                                text: 'Loading',
                                spinner: 'el-icon-loading',
                            });
                            this.$http({
                                method: 'put',
                                url: urlConfig.menuManage,
                                baseURL: '/api',
                                data:{
                                    "id": that.formData.id,
                                    "name": that.formData.name,
                                    "path": that.formData.path,
                                    "order": that.formData.orderid,
                                    "parentId": that.formData.parentId,
                                    "icon":that.formData.icon,
                                    "description":that.formData.description,
                                    "ifShow":ifShowNum,
                                    "enable":enableNum,
                                }
                            }).then(function(response){
                                if(response.data.code>199 && response.data.code<400) {
                                    if (!response.data.data) {
                                        return;
                                    }
                                    Message.success('修改成功');
                                    that.formData.id = response.data.data.id;
                                    that.oldId = that.formData.id;
                                    that.oldName = that.formData.name;
                                    that.oldPath = that.formData.path;
                                    that.oldorderid = that.formData.orderid;
                                    that.oldIcon = that.formData.icon;
                                    that.oldDescription = that.formData.description;
                                    that.menuRequest('',1);
                                }else{
                                    Message.error('修改失败');
                                }
                                loading.close();
                            }).catch(function(err){
                                Message.error('修改失败');
                                loading.close();
                            });
                        }
                    });
                }
            },
            getJsonTree(newdata,parentId){
                let that = this;
                let itemArr=[];
                for(let i=0;i<newdata.length;i++){
                    let node=newdata[i];
                    if(node.parentId==parentId ){
                        let newNode={
                            id:node.id,
                            name:node.name,
                            path:node.path,
                            orderid:node.orderid,
                            parentId:node.parentId,
                            icon:node.icon,
                            description:node.description,
                            ifShow:node.ifShow,
                            enable:node.enable,
                            children:that.getJsonTree(newdata,node.id)
                        };
                        itemArr.push(newNode);
                    }
                }
                itemArr.sort(that.up);
                return itemArr;
            },
            //发送菜单树查询请求
            menuRequest(id,editImg) {
                debugger;
                let that=this;
                const loading = that.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                        method:'get',
                        url:urlConfig.menuManage,
                        baseURL:'/api',
                        params:{
                            id:id
                        }
                    }
                ).then(function (response) {
                    if(response.data.code>199 && response.data.code<400) {
                        let newdata=response.data.data.menuInfos;
                        that.menuTreeData[0].children =that.getJsonTree(newdata, '-1');
                        for (let i = 0; i < that.menuTreeData[0].children.length; i++) {
                            that.menuTreeData[0].children[i].parentId = '0'
                        }

                    }else {
                        Message.error('获取失败')
                    }
                    loading.close();
                }).catch(function (err) {
                    Message.error('获取失败');
                    loading.close();
                });
            },
            up(x,y){
                return x.orderid-y.orderid
            },
            //重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            formChange(){
                debugger;
                let that =this;
                if(that.oldName!=that.formData.name||that.oldPath!=that.formData.path||that.oldorderid!=that.formData.orderid||that.oldIcon!=that.formData.icon||that.oldDescription!=that.formData.description||that.oldIfShow!=that.formData.ifShow||that.oldEnable!=that.formData.enable){
                    return false
                }else return true
            }
        },
        mounted() {
            this.menuRequest('',1)
        }
    }
</script>
.formLayoutW
<style scoped>
    .headerCoster{
        height: 59px;
        border-top: 1px solid #eee;
        border-bottom: 1px solid #eee;
    }

    .formLayoutW{
        width: 77%;
    }

    .leftMinWidth {
        min-width: 275px;
    }

    .cardAllWidth {
        width: 100%;
    }

    .autoHeight {
        min-height:calc(100vh - 180px);
    }

    .mt80 {
        margin-top: 80px;
    }

    .disFlex {
        display: flex;
    }

    .RightFlex {
        flex: 1;
    }
</style>